package com.example.app;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static net.sf.calibur.i18n.R.*;

class UserRecord {
	long id;
	String passwd;
	String name;

	UserRecord(long id, String name, String pwd) {
		this.id = id;
		this.passwd = pwd;
		this.name = name;
	}
}

public class PlayerFactory {
	static class SingletonHolder {
		static PlayerFactory instance = new PlayerFactory();
	}

	public static PlayerFactory getInstance() {
		return SingletonHolder.instance;
	}

	private Map<String, UserRecord> userTable;
	private Map<Long, Player> activePlayers;
	private Logger logger = LoggerFactory.getLogger(getClass());

	private PlayerFactory() {
		userTable = new HashMap<String, UserRecord>();
		userTable.put("john", new UserRecord(1, "约翰", "123456"));
		userTable.put("oliver", new UserRecord(2, "奥利福", "123456"));

		activePlayers = new ConcurrentHashMap<Long, Player>();
	}

	public Player playerLogin(String passport, String passwd)
			throws UserOperationException {
		UserRecord rec = userTable.get(passport);
		if (rec == null) {
			throw new UserOperationException("用户passport ID " + passport
					+ " 不存在");
		}

		if (!passwd.equals(rec.passwd)) {
			logger.info(_("input user password=[%s] record passwod=[%s]", passwd, rec.passwd));
			throw new UserOperationException("用户密码错误");
		}

		Player player = activePlayers.get(rec.id);
		if (player != null) {
			throw new UserOperationException("用户已经登录，不能重复登录。");
		}

		player = new Player(rec.id, rec.name);
		activePlayers.put(player.getId(), player);
		return player;
	}

	public void playerLogout(Player player) {
		activePlayers.keySet().remove(player.getId());
	}
}
